package com.toommi.refuse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.toommi.refuse.common.enums.SuggestionTypeEnum;
import com.toommi.refuse.entity.Suggestion;
import com.toommi.refuse.entity.SuggestionExample;
import com.toommi.refuse.mapper.SuggestionMapper;
import com.toommi.refuse.service.SuggestionService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangg
 * @since 2019-07-25 17:07
 */
@Service
@AllArgsConstructor
public class SuggestionServiceImpl implements SuggestionService {

    private SuggestionMapper suggestionMapper;

    @Override
    public void addSuggestion(Suggestion suggestion) {
        suggestion.setCreateTime(System.currentTimeMillis());
        suggestion.setUpdateTime(System.currentTimeMillis());

        suggestionMapper.insert(suggestion);
    }

    @Override
    public PageInfo<Suggestion> findSuggestions(int pageNum, int pageSize, String keyWord, int type, long wechatUserId) {

        PageHelper.startPage(pageNum, pageSize);
        List<Suggestion> suggestionList;
        SuggestionExample example = new SuggestionExample();
        if (StringUtils.isNotEmpty(keyWord)) {
            example.createCriteria().andContentLike("%" + keyWord + "%").andTypeEqualTo(type);
        } else {
            example.createCriteria().andTypeEqualTo(type);
        }
        if (wechatUserId > 0) {
            example.createCriteria().andWechatUserIdEqualTo(wechatUserId);
        }
        suggestionList = suggestionMapper.selectByExample(example);
        return new PageInfo<>(suggestionList);
    }

    @Override
    public List<Suggestion> findSuggetionDetail(int suggestionId) {
        Suggestion suggestion = suggestionMapper.selectByPrimaryKey((long)suggestionId);
        if(suggestion==null){
            return new ArrayList<>();
        }
        List<Suggestion> suggestionList = new ArrayList<>(2);
        suggestionList.add(suggestion);
        SuggestionExample example = new SuggestionExample();
        example.createCriteria().andSuggestIdEqualTo((long) suggestionId).andTypeEqualTo(SuggestionTypeEnum.REPLY.getType());

        Suggestion reply = suggestionMapper.selectOneByExample(example);
        if(reply!=null){
            suggestionList.add(reply);
        }

        return suggestionList;
    }
}
